var $datatable;
var _DATATABLE_TR;
var _MAKY;
var _MANGUOIBAN;
var _STT;
var oTable;

$(document).ready(function() {
    _MAKY = $('input#maky[name=maky]').val();

    $datatable = $('#datatable_nb');

    oTable = $datatable.dataTable({
        "bPaginate": false,
        "bFilter" : false,
        "bSort": false,
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bInfo": false,
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": $('#datatable_nb').attr('active_url'),        
        "fnDrawCallback": function( oSettings ) {
            $("#datatable_nb_wrapper").find(".fg-toolbar").removeClass("ui-widget-header");
            datatable_selected();
        },
        "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
            $(nRow).attr("stt",iDisplayIndex);
            
            if( aData['matiendien'] != undefined ){
                $(nRow).attr("value_id",aData['matiendien']);
            }
            if( aData['action'] != undefined ){
                $(nRow).attr("action",aData['action']);
            }
            if( aData['manguoiban'] != undefined ){
                $(nRow).attr("nguoiban",aData['manguoiban']);
            }
            
            //if ( aData[4] == "A" ){$('td:eq(4)', nRow).html( '<b>A</b>' );}
            return nRow;
        }
        //"oTableTools": {"aButtons": ["copy", "csv", "xls", "pdf"]}
        
    });

    dialogFormAddNewNB();
    dialogConfrimDeleteNB();
    dialogFormEditNB();
    dialogError();
} );

function datatable_selected(){
    $datatable.find('tbody tr').click( function( e ) {
        if ( $(this).hasClass('row_selected') ) {
            $(this).removeClass('row_selected');
            _DATATABLE_TR = null;
            _STT = null;
        }else {
            oTable.$('tr.row_selected').removeClass('row_selected');
            $(this).addClass('row_selected');
            _DATATABLE_TR = $(this).attr('value_id');
            _STT = $(this).attr('stt');
        }
    });
    
    $datatable.find('tbody tr').bind("dblclick", function(){
        if ( !$(this).hasClass('row_selected') ) {
            $(this).addClass('row_selected');
        }
        _DATATABLE_TR = $(this).attr('value_id');
        _MANGUOIBAN = $(this).attr('nguoiban');
        
        if(_DATATABLE_TR != 0){
            edit_nbdk_dbclick( _DATATABLE_TR, _MAKY, _MANGUOIBAN );
        }else{
            insert_nbdk_dbclick( _DATATABLE_TR, _MAKY, _MANGUOIBAN );
        }
        
        
    });

}

function dialogFormAddNewNB(){
    
    $( "#dialog_form_add" ).dialog({
        autoOpen: false,
        //height: 300,
        width: 620,
        modal: true,
        resizable: true,
        buttons: {
            "Save": function() {
                var $this = $( this );
                $("#frm_nb").ajaxSubmit({
                    //beforeSubmit: validate
                    dataType:  'json',
                    beforeSubmit: function(formData, jqForm, options) {
                        return validate_form_tiendien();
                    },
                    success: function(data) {
                        if(data.action == 'insert'){
                            //oTable.fnDraw();
                            //oTable.fnFilter( data.ten );
                            //oTable.fnSort( [ [0,'desc'] ] );
                            var $tr = oTable.$('tr[stt="'+ _STT +'"]');
                            $tr.attr('value_id',data.id)
                            $tr.attr('action','update')
                            $tr.find('td:eq(2)').html(data.sodien_moi);
                            $tr.find('td:eq(3)').html(data.sodien_cu);
                            $tr.find('td:eq(4)').html(data.sotieuthu_cu);
                            $tr.find('td:eq(5)').html(data.socaodiem_cu);
                            $tr.find('td:eq(6)').html(data.sotieuthu_moi);
                            $tr.find('td:eq(7)').html(data.socaodiem_moi);
                            $tr.find('td:eq(8)').html(data.thanhtien_bt);
                            $tr.find('td:eq(9)').html(data.thanhtien_cd);
                            $tr.find('td:eq(10)').html(data.thanhtien);
                        }else if(data.action == 'update'){
                            
                        }
                        $this.dialog( "close" );
                    }
                });
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
            $("#dialog_form_add").html('');
        }
    });
        
}

function dialogFormEditNB(){
    
    $( "#dialog_form_edit" ).dialog({
        autoOpen: false,
        //height: 300,
        width: 570,
        modal: true,
        resizable: true,
        buttons: {
            "Save": function() {
                var $this = $( this );
                $("#frm_nb").ajaxSubmit({
                    //beforeSubmit: validate
                    dataType:  'json',
                    beforeSubmit: function(formData, jqForm, options) {
                        return validate_form_tiendien();
                    },
                    success: function(data) {
                        if(data.action == 'insert'){
                            oTable.fnDraw();
                        }else if(data.action == 'update'){
                            var $tr = oTable.$('tr[value_id="'+ data.id +'"]');
                            $tr.find('td:eq(2)').html(data.sodien_moi);
                            $tr.find('td:eq(3)').html(data.sodien_cu);
                            $tr.find('td:eq(4)').html(data.sotieuthu_cu);
                            $tr.find('td:eq(5)').html(data.socaodiem_cu);
                            $tr.find('td:eq(6)').html(data.sotieuthu_moi);
                            $tr.find('td:eq(7)').html(data.socaodiem_moi);
                            $tr.find('td:eq(8)').html(data.thanhtien_bt);
                            $tr.find('td:eq(9)').html(data.thanhtien_cd);
                            $tr.find('td:eq(10)').html(data.thanhtien);
                        }
                        $this.dialog( "close" );
                    }
                });
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
            $("#dialog_form_edit").html('');
        }
    });
        
}

function dialogConfrimDeleteNB(){
    
    $( "#dialog_confrim_delete" ).dialog({
        autoOpen: false,
        //height: 300,
        width: 320,
        modal: true,
        resizable: true,
        buttons: {
            "Delete": function() {
                var url = $("#dialog_confrim_delete").attr('active_url');
                
                $.post(url, { id: _DATATABLE_TR },function(data){
                     //alert(data.message);
                     oTable.fnDraw();
                }, "json");
                
                $( this ).dialog( "close" );
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
            //allFields.val( "" ).removeClass( "ui-state-error" );
        }
    });
        
}

function add_nb(){
    var url = $("#dialog_form_add").attr('active_url');
        
    $.get(url, function(data) {
        $( "#dialog_form_add" ).html( data );
        $( "#dialog_form_add" ).dialog( "open" );
    });
}

function delete_nb(){
    if(_DATATABLE_TR != null){
        $( "#dialog_confrim_delete" ).dialog( "open" );
    }else{
        $( "#dialog_error" ).html( "Chua chon item" );
        $( "#dialog_error" ).dialog( "open" );
    }
        
}

function edit_nb(){
    if(_DATATABLE_TR != null){
        var url = $("#dialog_form_edit").attr('active_url') + '/' + _DATATABLE_TR;
        
        $.get(url, function(data) {
            $( "#dialog_form_edit" ).html( data );
            $( "#dialog_form_edit" ).dialog( "open" );
        });
    }else{
        $( "#dialog_error" ).html( '<div>Chua chon item Chua chon item Chua chon item<div>' );
        $( "#dialog_error" ).dialog( "open" );
    }
        
}

function edit_nbdk_dbclick(id,maky,manguoiban){
    var url = $("#dialog_form_edit").attr('active_url') + '/' + id + '/' + maky + '/' + manguoiban;
        
    $.get(url, function(data) {
        $( "#dialog_form_edit" ).html( data );
        check_keyboard_number();
        $( "#dialog_form_edit" ).dialog( "open" );
    });
}

function insert_nbdk_dbclick(id,maky,manguoiban){
    var url = $("#dialog_form_add").attr('active_url') + '/' + id + '/' + maky + '/' + manguoiban;
        
    $.get(url, function(data) {
        $( "#dialog_form_add" ).html( data );
        check_keyboard_number();
        $( "#dialog_form_add" ).dialog( "open" );
    });
}

function check_keyboard_number(){
    $(".validate-number").unbind('keydown').keydown(function(e){
       //console.log(e.keyCode);
       var flag = e.keyCode >= 48 && e.keyCode <= 57;
       flag |= e.keyCode == 8;
       //flag |= e.keyCode == 190; // dot
       flag |= e.keyCode == 35; // END
       flag |= e.keyCode == 36; // HOME
       flag |= (e.keyCode >= 37 && e.keyCode <= 40);
       flag |= (e.keyCode >= 96 && e.keyCode <= 105);
       flag |= e.which >= 48 && e.which <= 57;
       flag |= e.which == 8;//Backspace
       flag |= (e.which >= 37 && e.which <= 40);
       flag |= (e.which >= 96 && e.which <= 105);
       flag |= e.keyCode == 13;//Enter
       flag |= e.which == 46;//Delete
       if(flag != true && flag != 1){
            return false;
       }
   });
}

function validate_form_tiendien(){
    var flag = true;
    var sodien_moi = $('input[name=sodien_moi]').val(); 
    var sodien_cu = $('input[name=sodien_cu]').val(); 
    var sotieuthu_cu = $('input[name=sotieuthu_cu]').val(); 
    var socaodiem_cu = $('input[name=socaodiem_cu]').val(); 
    
    if(sodien_moi == ''){
        $("input[name=sodien_moi]").addClass("i-error");
        $("#isodien_moi").show();
        flag = false;
    }else{
        $("#isodien_moi").hide();
        $("input[name=sodien_moi]").removeClass("i-error");
    }
    
    if(sodien_cu == ''){
        $("input[name=sodien_cu]").addClass("i-error");
        $("#isodien_cu").show();
        flag = false;
    }else{
        $("#isodien_cu").hide();
        $("input[name=sodien_cu]").removeClass("i-error");
    }
    
    if(sotieuthu_cu == ''){
        $("input[name=sotieuthu_cu]").addClass("i-error");
        $("#isotieuthu_cu").show();
        flag = false;
    }else{
        $("#isotieuthu_cu").hide();
        $("input[name=sotieuthu_cu]").removeClass("i-error");
    }
    
    if(socaodiem_cu == ''){
        $("input[name=socaodiem_cu]").addClass("i-error");
        $("#isocaodiem_cu").show();
        flag = false;
    }else{
        $("#isocaodiem_cu").hide();
        $("input[name=socaodiem_cu]").removeClass("i-error");
    }
    
    if( parseInt(sodien_moi)  < parseInt(sodien_cu)){
        $("input[name=sodien_moi]").addClass("i-error");
        $("input[name=sodien_cu]").addClass("i-error");
        flag = false;
        $("#error-mesg").html('Chi so dien ke moi ko the be hon chi so cu');
        $("#error-mesg").show();
    }
    else{
        $("#error-mesg").hide();
        //$("input[name=sodien_moi]").removeClass("i-error");
        //$("input[name=sodien_cu]").removeClass("i-error");
    }
    return flag;
}